<template name="chat">
    <view class="app-container">
        <!-- 左侧用户列表 -->
        <view class="user-list-panel">
            <!-- 当前用户身份信息 -->
            <view class="current-user-card">
                <image class="avatar" :src="currentUser.avatar"></image>
                <view class="user-info">
                    <text class="user-name">{{ currentUser.name }}</text>
                    <!-- <text class="user-title">{{ currentUser.title }}</text> -->
                </view>
                <view class="user-switcher" @tap="toggleUserSwitcher">
                    <text>▼</text>
                </view>
                
                <!-- 用户切换下拉框 -->
                <view class="user-switcher-dropdown" v-if="showUserSwitcher">
                    <view 
                        class="switcher-item" 
                        v-for="user in availableUsers" 
                        :key="user.id"
                        @tap="switchUser(user)"
                    >
                        <image class="avatar" :src="user.avatar"></image>
                        <text class="name">{{ user.name }}</text>
                    </view>
                </view>
				
				<view class="actions">
				    <view class="action-btn" @tap="toggleBulkSendMode">
				        <text>{{ bulkSendMode ? '✕' : '📤' }}</text>
				    </view>
				</view>
            </view>

            <view class="search-box">
                <text class="search-icon">🔍</text>
                <input type="text" placeholder="搜索联系人..." v-model="searchQuery" @input="searchUsers">
            </view>

            <view class="section-title">
                <text class="section-title-text">联系人列表</text>
                <view class="section-title-actions">
                    <text class="user-count">{{ users.length }} 人</text>
                 
                </view>
            </view>
            
            <scroll-view class="users-list" scroll-y>
                <view 
                    class="user-item" 
                    v-for="user in users" 
                    :key="user.id"
                    :class="{ active: activeUser.id === user.id && !bulkSendMode }"
                    @tap="selectUser(user)"
                >
                    
                    <image class="avatar" :src="user.avatar"></image>
                    <view class="user-details">
                        <text class="user-name">{{ user.name }}</text>
                        <text class="user-content" v-if="user.contentType">{{ user.contentType === 'text' ? user.content: (user.content.length>0 ?'[图片]':'') }}</text>
                    </view>
                    <view class="unread-badge" v-if="user.unread > 0 && !bulkSendMode">{{ user.unread }}</view>
                </view>
            </scroll-view>
        </view>
        
        <!-- 聊天区域 -->
        <view class="chat-panel">
            <view class="chat-header">
                <image class="avatar" :src="activeUser.avatar" @click="previewImage(activeUser.avatar)"></image>
                <view class="chat-header-info">
                    <text class="chat-user-name" v-if="!bulkSendMode">{{ activeUser.name }}</text>
                    <text class="chat-user-name" v-else>群发消息</text>
                </view>
            </view>
            
            <scroll-view class="chat-messages" scroll-y :scroll-top="scrollTop" scroll-with-animation 
                :scroll-into-view="scrollId">
                <!-- 预约发布界面 -->
                <view v-if="!bulkSendMode && activeUser.id === '-1'">
                
                    
                    <view class="schedule-items">
                        <view class="schedule-item" v-for="(item, index) in messages" :key="index">
                            <view class="schedule-content">
                                <text v-if="item.contentType === 'text'">{{ item.content }}</text>
                                <image v-else :src="item.content" @click="previewImage(item.content)" mode="aspectFit" class="schedule-image"></image>
                            </view>
                            <view class="schedule-time">
                                <text>发布时间: {{ item.time }}</text>
                            </view>
                            <view class="schedule-actions">
                                
                                <button class="delete-btn" @tap="deleteScheduleItem(index)">删除</button>
                            </view>
                        </view>
                    </view>
                    
                    <view v-if="messages.length === 0" class="empty-schedule">
                        <text>暂无预约发布内容</text>
                    </view>
                </view>
                
                <!-- 普通聊天界面 -->
                <view v-else>
                    <view v-if="!bulkSendMode">
                        <view 
                            class="message" 
                            :class="item.mode === 'user' ? 'sent' : 'received'"
                            v-for="(item,index) in messages"
                            :key="index"
                            :id="`s${item.id}`"
                        >
                            <view class="message-avatar">
                                <image class="avatar" @click="previewImage(currentUser.avatar)" v-if="item.mode === 'user'" :src="currentUser.avatar"></image>
                                <image class="avatar" @click="previewImage(item.avatar)" v-if="item.mode != 'user'" :src="item.avatar"></image>
                            </view>
                            <view class="message-content">
                                <!-- 文字消息 - 简化气泡 -->
                                <text class="content" selectable="true" v-if="item.contentType === 'text'">{{ item.content }}</text>
                                
                                <!-- 图片消息 - 直接显示图片 -->
                                <image 
                                    v-else 
									@click="previewImage(item.content)"
                                    :src="item.content" 
                                    mode="aspectFit" 
                                    class="message-image"
                                    :class="item.mode === 'user' ? 'sent-image' : 'received-image'"
                                ></image>
                                
                                <text class="time">{{ item.time }}</text>
                            </view>
                        </view>
                    </view>
                    
                    <view v-else class="bulk-message-preview">
                        <view class="bulk-recipients">
                            <text>将发送给全站用户。封禁，未审核通过的除外</text>
                      
                        </view>
                    </view>
                </view>
            </scroll-view>
            
            <view class="message-input-area">
                <!-- 图片选择按钮 -->
                <view class="image-picker-btn" @tap="chooseImage" v-if="activeUser.id !== '-1'">
                    <text>📷</text>
                </view>
                
                
                <textarea 
                    auto-height
                    :placeholder="bulkSendMode ? '输入群发消息内容...' : '输入消息...'" 
                    v-model="newMessage"
                    @confirm="sendMessage"
                    class="message-input"
					maxlength="-1"
                />
                
                <button class="send-button" @tap="sendMessage">
                    <text>发送</text>
                </button>
            </view>
        </view>
    </view>
</template>

<script>
    export default {
        name: 'chat',
        data() {
            return {
                scrollId: '',
                searchQuery: '',
                activeUser: {},
                newMessage: '',
                bulkSendMode: false,
                scrollTop: 0,
                users: [],
                messages: [],
                isSearching: false,
         
                editingScheduleIndex: -1, // 当前编辑的预约项索引
              
                showUserSwitcher: false, // 用户切换下拉框
                
                currentUser: {}, // 当前用户身份
                availableUsers: [] // 可切换的用户身份
                    
            }
        },
        created() {
            this.loadUser();
			this.$routeData.loadHeader()
		
			this.currentUser = this.$routeData.GetUserData();
        },
 
        methods: {
			
			//预览图片
			previewImage(url) {
				const urls = [];
				urls.push(url);
				uni.previewImage({
					urls: urls,
					indicator: "number"
				})
			},
            // 加载用户列表
            loadUser() {
                var that = this;
                that.$common.get_request(
                    {
                        type: 'getchatList',
                        user_id: this.currentUser.id ? this.currentUser.id:'',
                    },
                    (res) => {
						let data = {
							    id: '-1',
							    name: '预约发布',
							    avatar: '/static/img/message.png',
							    content: '新用户自动进行发送',
							    unread: 0,
							    selected: false,
								contentType:'text'
						}
						// 添加预约发布用户
                        let index = this.GetChrckYuYue(res.list);
						if(index < 0 ){
							res.list.unshift(data);
						}else{
							res.list[index] = data
						}
                        that.users = res.list;
                        if (res.list.length > 1) {
                            that.selectUser(res.list[1]);
                        }
                    }
                );
            },
            GetChrckYuYue(list){
				for(var i=0;i<list.length;i++){
					if(list[i].id == '-1'){
						return i
					}
				}
				return -1
			},
            // 网络搜索用户
            searchUsers() {
                if (!this.searchQuery.trim()) {
                    // 清空搜索条件时加载默认用户列表
                    this.loadUser();
                    
                    return;
                }
                
                this.isSearching = true;
                
                // 发起网络搜索请求
                this.$common.get_request(
                    {
                        type: 'firm_user_list',
                        search: this.searchQuery
                    },
                    (res) => {
                        this.isSearching = false;
                        // 将搜索结果赋值给users数组
                        this.users = res.list
                    }
                );
            },
           
            
            // 选择用户并加载聊天记录
            selectUser(user) {
               
                this.activeUser = user;
                user.unread = 0;
                
                // 加载聊天记录
                this.loadMore(this.currentUser.id,user.id);
                
                this.scrollToBottom();
            },
            
            // 加载聊天记录
            loadMore(user_id,send_id) {
                var that = this;
                that.$message.getUnreadList(
					send_id,user_id,
                    (res) => {
                        if (res.send_id == this.activeUser.id) {
                            that.messages = res.list;
                            this.$nextTick(() => {
                                this.scrollToBottom();
                            });
                        }
                    }
                );
            },

            
            // 选择图片
            chooseImage() {
                uni.chooseImage({
                    count: 1,
                    sizeType: ['compressed'],
                    sourceType: ['album', 'camera'],
                    success: (res) => {
                        const tempFilePaths = res.tempFilePaths;
                        if (tempFilePaths.length > 0) {
                            this.sendImage(tempFilePaths[0]);
                        }
                    }
                });
            },

            // 发送图片
            sendImage(imagePath) {
          
                
                const now = new Date();
                const timeString = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
                
                const newMsg = {
                    id: Date.now(),
                    mode: 'user',
                    contentType: 'image',
                    content: imagePath,
                    time: timeString
                };
                
                this.messages.push(newMsg);
                this.$message.sendImage(this.activeUser.id, imagePath,this.currentUser.id,this.currentUser.name,this.currentUser.avatar,(this.bulkSendMode?'bulkSendMode':''));
                if(this.bulkSendMode == true){
                	uni.showToast({
                	    title: '发送群发成功',
                	    icon: 'success'
                	});
                }
                this.scrollToBottom();
            },
            
            // 发送消息
            sendMessage() {
                if (!this.newMessage.trim() && this.activeUser.id !== '-1') return;
            
                
              
                
                const now = new Date();
                const timeString = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;

                const newMsg = {
                    id: Date.now(),
                    mode: 'user',
                    contentType: 'text',
                    content: this.newMessage,
                    time: timeString
                };
				this.messages.push(newMsg);
                
                this.$message.sendMessage(this.activeUser.id, this.newMessage,this.currentUser.id,this.currentUser.name,this.currentUser.avatar,(this.bulkSendMode?'bulkSendMode':''));

                this.newMessage = '';
				
				if(this.bulkSendMode == true){
					uni.showToast({
					    title: '发送群发成功',
					    icon: 'success'
					});
				}
                this.scrollToBottom();
            },
            //群发消息开关
            toggleBulkSendMode() {
                this.bulkSendMode = !this.bulkSendMode;
            },
          
         
            
            // 删除预约发布项
            deleteScheduleItem(index) {
                var that = this;
                this.$message.deleteMessage(
                	that.messages[index].id,
                    (res) => {
						that.messages.splice(index, 1);
						that.$common.toast(res.msg)

                    }
                );
            },
            
          
            
            // 切换用户身份下拉框
            toggleUserSwitcher() {
                this.showUserSwitcher = !this.showUserSwitcher;
				if( this.showUserSwitcher == true){
					let list1 = []
					list1.push(this.$routeData.GetUserData())
					let list2 = this.$routeData.GetHeader();
					this.availableUsers = [...list1, ...list2];
				
				}
				
            },
            
            // 切换用户身份
            switchUser(user) {
                this.currentUser = user;
                this.showUserSwitcher = false;
				this.loadUser()
				console.log('已切换到',user)
                uni.showToast({
                    title: `已切换到 ${user.name}`,
                    icon: 'success'
                });
            },
            
            scrollToBottom() {
                this.$nextTick(() => {
                    this.scrollTop = 99999;
                    if (this.messages.length > 0) {
                        this.scrollId = `s${this.messages[this.messages.length - 1].id}`;
                    }
                });
            }
        },
        mounted() {
            // 默认选择第一个用户
            if (this.users.length > 0) {
                this.activeUser = this.users[0];
                this.users[0].unread = 0;
            }
            
            // 初始滚动到底部
            this.scrollToBottom();
        }
    }
</script>

<style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
    }
    
    .app-container {
        display: flex;
        height: calc(100vh - 20px);
        width: calc(100% - 20px);
        background-color: #f5f7fb;
        position: relative;
    }
    
    /* 当前用户身份卡片 */
    .current-user-card {
        position: relative;
        padding: 15px;
        background: #ffffff;
        border-bottom: 1px solid #e0e0e0;
        display: flex;
        align-items: center;
        z-index: 10;
		gap:10px;
    }
    
    .current-user-card .avatar {
        width: 42px;
        height: 42px;
        border-radius: 50%;
    }
    
    .user-info {
        flex: 1;
    }
    
    .user-info .user-name {
        font-size: 16px;
        font-weight: 600;
        color: #333333;
        display: block;
    }
    
    .user-info .user-title {
        font-size: 13px;
        color: #666666;
        display: block;
    }
    
    .user-switcher {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background: #f5f5f5;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        font-size: 14px;
    }
    
    .user-switcher-dropdown {
        position: absolute;
        top: 70px;
        left: 15px;
        right: 15px;
        background: #ffffff;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        z-index: 100;
        padding: 10px;
    }
    
    .switcher-item {
        display: flex;
        align-items: center;
        padding: 10px;
        border-radius: 6px;
        cursor: pointer;
    }
    
    .switcher-item:hover {
        background: #f5f7fb;
    }
    
    .switcher-item .avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        margin-right: 10px;
    }
    
    .switcher-item .name {
        font-size: 15px;
        color: #333333;
    }
    
    /* 搜索遮罩层 */
    .search-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        z-index: 50;
    }
    
    /* 左侧用户列表样式 */
    .user-list-panel {
        width: 320px;
        background: #ffffff;
        border-radius: 10px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
        display: flex;
        flex-direction: column;
        margin-right: 20px;
        overflow: hidden;
    }

    
  
    
 
 
    
    .actions {
        display: flex;
        gap: 15px;
    }
    
    .action-btn {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background: #f5f5f5;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 18px;
    }
    
    .action-btn:hover {
        background: #e6f0ff;
    }
    
    .avatar {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: linear-gradient(135deg, #0f66e0, #3b82f6);
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 500;
        font-size: 18px;
        color: white;
    }
    

    
    .user-name {
        font-size: 18px;
        margin-bottom: 5px;
        color: #333333;
        display: block;
    }
    
    .user-content {
	   font-size: 13px;
	   color: #666666;
	   display: block;
	   position: relative;
	   /* justify-content: center; */
	   display: flex;
	   /* flex-direction: column; */
	   text-overflow: ellipsis;
	   white-space: nowrap;
	   overflow: hidden;
	   height: 25px;
    }
    
    .search-box {
        margin: 20px;
        position: relative;
        display: flex;
        align-items: center;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        background: #f5f5f5;
        height: 44px;
    }
    
    .search-icon {
        padding: 0 10px;
        font-size: 18px;
        color: #999;
    }
    
    .search-box input {
        flex: 1;
        height: 100%;
        padding: 0;
        border: none;
        background: transparent;
        color: #333333;
        font-size: 14px;
        outline: none;
    }
    
    .section-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 0 20px 15px;
    }
    
    .section-title-text {
        font-size: 18px;
        font-weight: 600;
        color: #333333;
    }
    
    .section-title-actions {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .user-count {
        background-color: #e6f0ff;
        color: #0f66e0;
        font-size: 12px;
        font-weight: 500;
        padding: 4px 10px;
        border-radius: 12px;
    }
    
    
    .users-list {
        flex: 1;
        overflow-y: auto;
        padding: 0 15px 15px;
    }
    
    .user-item {
        display: flex;
        align-items: center;
        gap: 15px;
        padding: 12px 15px;
        border-radius: 8px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    
    .user-item:hover {
        background: #f5f5f5;
    }
    
    .user-item.active {
        background: #e6f0ff;
    }
    
    .user-item .avatar {
        width: 42px;
        height: 42px;
        font-size: 16px;
		display: flex;
		flex: none;
    }
    
  
    
    .unread-badge {
        background-color: #0f66e0;
        color: white;
        font-size: 12px;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 10px;
    }
  
    
    /* 聊天区域样式 */
    .chat-panel {
        flex: 1;
        display: flex;
        flex-direction: column;
        background: #ffffff;
        border-radius: 10px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
        overflow: hidden;
    }
    
    .chat-header {
        padding: 16px 25px;
        display: flex;
        align-items: center;
        gap: 15px;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .chat-header-info {
        flex: 1;
    }
    
    .chat-user-name {
        font-size: 18px;
        margin-bottom: 3px;
        color: #333333;
        display: block;
    }
    
    .chat-user-status {
        color: #666666;
        font-size: 14px;
        display: block;
    }
    
    .chat-messages {
        flex: 1;
        padding: 20px 25px;
        overflow-y: auto;
        display: flex;
        flex-direction: column;
        gap: 16px;
        background-color: #f5f7fb;
    }
    
    .message {
        display: flex;
        max-width: 100%;
        padding: 10px 0;
        position: relative;
        animation: fadeIn 0.3s ease;
    }
    
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .message.sent {
        flex-direction: row-reverse;
    }
    
    .message.received {
        flex-direction: row;
    }
    
    .message-avatar {
        width: 40px;
        height: 40px;
        margin: 0 10px;
    }
    
    .message-content {
        max-width: 65%;
        padding: 8px 12px;
        border-radius: 12px;
        position: relative;
    }
    
    .message.sent .message-content {
        background: #0f66e0;
        color: white;
    }
    
    .message.received .message-content {
        background: #ffffff;
        border: 1px solid #e0e0e0;
    }
    
    .content {
            font-size: 16px;
            line-height: 1.4;
            display: block;
            position: relative;
            justify-content: center;
            /* display: flex
        ; */
            flex-direction: column;
            text-overflow: ellipsis;
            white-space: break-spaces;
            /* overflow: hidden; */
            /* display: flex
        ; */
            word-wrap: break-word;
            overflow-wrap: break-word;
    }
    
    .time {
        font-size: 12px;
        color: rgba(255, 255, 255, 0.8);
        text-align: right;
        margin-top: 6px;
        display: block;
    }
    
    .message.received .time {
        color: #999999;
    }
    
    .message-image {
        max-width: 100%;
        max-height: 200px;
        border-radius: 8px;
        display: block;
        margin-bottom: 5px;
    }
    
    .sent-image {
        border: 1px solid #0f66e0;
    }
    
    .received-image {
        border: 1px solid #e0e0e0;
    }
    
    .message-input-area {
        padding: 15px 25px;
        display: flex;
        gap: 12px;
        border-top: 1px solid #e0e0e0;
        background: #ffffff;
        align-items: center;
    }
    
    .image-picker-btn {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: #f5f5f5;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        font-size: 20px;
        transition: all 0.3s ease;
        flex-shrink: 0;
    }
    
    .image-picker-btn:hover {
        background: #e6f0ff;
    }
    
    .message-input {
		min-height: 40px;
        flex: 1;
        padding: 14px 18px;
        border-radius: 24px;
        background: #f5f5f5;
        border: 1px solid #e0e0e0;
        color: #333333;
        font-size: 16px;
        outline: none;
        transition: all 0.3s ease;
        min-height: 48px;
        resize: none;
		height: auto;
    }
    
    .message-input:focus {
        border-color: #0f66e0;
        box-shadow: 0 0 0 2px rgba(15, 102, 224, 0.2);
    }
    
    .send-button {
        padding: 0 20px;
        height: 48px;
        border-radius: 24px;
        background: #0f66e0;
        color: white;
        border: none;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        transition: all 0.3s ease;
        flex-shrink: 0;
    }
    
    .send-button:hover {
        background: #0c54b3;
        transform: scale(1.05);
    }
    
    .bulk-message-preview {
        display: flex;
        flex-direction: column;
        gap: 20px;
    }
    
    .bulk-recipients {
        background: #ffffff;
        border-radius: 10px;
        padding: 15px;
        border: 1px solid #e0e0e0;
    }
    

    

    
    .schedule-items {
        display: flex;
        flex-direction: column;
        gap: 15px;
    }
    
    .schedule-item {
        background: #ffffff;
        border-radius: 8px;
        padding: 15px;
        border: 1px solid #e0e0e0;
    }
    
    .schedule-content {
        margin-bottom: 10px;
        font-size: 16px;
    }
    
    .schedule-image {
        max-width: 100%;
        max-height: 200px;
        border-radius: 8px;
    }
    
    .schedule-time {
        color: #666666;
        font-size: 14px;
        margin-bottom: 10px;
    }
    
    .schedule-actions {
        display: flex;
        gap: 10px;
    }
    
    .delete-btn {
        padding: 6px 12px;
        border-radius: 4px;
        font-size: 14px;
        cursor: pointer;
    }

    
    .delete-btn {
        background: #ffebee;
        color: #f44336;
        border: none;
    }
    
    .empty-schedule {
        text-align: center;
        padding: 40px 0;
        color: #999999;
    }
    
    /* 滚动条样式 */
    ::-webkit-scrollbar {
        width: 8px;
    }
    
    ::-webkit-scrollbar-track {
        background: transparent;
    }
    
    ::-webkit-scrollbar-thumb {
        background: rgba(0, 0, 0, 0.1);
        border-radius: 4px;
    }
    
    ::-webkit-scrollbar-thumb:hover {
        background: rgba(0, 0, 0, 0.15);
    }
</style>